<template>
  <a-layout>
    <PageHeader @back="$router.go(-1)" subTitle="返回"> 员工定薪 </PageHeader>
    <a-layout>
      <a-layout-sider width="276" class="border-r-line ta-center">
        <div class="file-user" style="margin-top: 40px">
          <a-row class="file-user-head" style="padding-left: 30px; padding-right: 30px">
            <a-col style="height: 170px">
              <a-row class="pd_b10">
                <strong style="font-size: 20px">{{ routerData.name }}</strong>
              </a-row>
              <a-row class="pd_b10" style="padding-top: 6px; padding-bottom: 25px; color: #adadad">
                {{ routerData.depName ? routerData.depName : "暂无" }}
                <a-divider type="vertical" />
                {{ routerData.positionName ? routerData.positionName : "暂无" }}
              </a-row>
              <a-row>
                <p style="color: #adadad; padding-bottom: 20px; position: absolute; left: 30px; top: 0px">
                  入职日期:
                  <span style="color: #222426">{{ formatDate(Number(routerData.joinDate), "d") }}</span>
                </p>

                <p style="color: #adadad; padding-bottom: 20px; position: absolute; left: 30px; top: 35px">
                  工作性质：<span style="color: #222426">{{ postType[routerData.postType - 1] }}</span>
                </p>

                <p style="color: #adadad; padding-bottom: 20px; position: absolute; left: 30px; top: 70px">
                  员工状态：<span style="color: #222426">{{ ["试用", "正式"][routerData.formalType - 1] }}</span>
                </p>
              </a-row>
            </a-col>
            <a-divider />
          </a-row>
        </div>
      </a-layout-sider>
      <a-layout-content class="ph24 mb100">
        <a-form-model ref="ruleForm" style="margin-top: 25px" :model="form">
          <a-form-model-item
            ref="template"
            label="定薪模板"
            prop="template"
            :rules="{
              required: true,
              message: '必选'
            }"
          >
            <div>
              <a-button
                v-for="(item, index) in templateList"
                :key="index"
                value="horizontal"
                class="modelBotton"
                :class="item.style"
                @click="templateChange(item.id, index, item)"
              >
                {{ item.name }}
              </a-button>
              <a-button type="link" class="add-field-add" @click="goIncrease()">
                <a-icon type="plus-circle" class="add-field-icon" />新增模板
              </a-button>
            </div>
          </a-form-model-item>
          <a-form-model-item
            ref="detailsList"
            label="定薪明细"
            prop="detailsList"
            :rules="{
              required: true,
              message: '必填'
            }"
          >
            <a-table :columns="columns" row-key="itemName" :data-source="detailsList" :pagination="false">
              <template v-for="col in ['trial', 'formal']" :slot="col" slot-scope="text, record">
                <div :key="col">
                  <a-input-number
                    v-if="record.isSum !== '1'"
                    :value="text"
                    :min="0"
                    :step="1"
                    :max="100000"
                    :precision="2"
                    style="margin: -5px 0; width: 120px"
                    @change="(value) => handleInputChange(value, record.projectId, col)"
                    >{{ text }}</a-input-number
                  >
                  <span v-else>{{ text.toFixed(2) }}</span>
                </div>
              </template>
            </a-table>
          </a-form-model-item>
          <a-form-model-item>
            <label><span style="color: red">* </span><span style="color: rgba(0, 0, 0, 0.85)"> 定薪原因： </span></label>
            <span style="margin-left: 10px"> 入职定薪</span>
          </a-form-model-item>
          <a-form-model-item ref="remark" prop="remark" label="备注" :label-col="{ span: 1 }" :wrapper-col="{ span: 13 }">
            <!-- <label>备注：</label> -->
            <a-textarea v-model="form.remark" style="width: 400px" :max-length="50" />
            <a-row style="width: 405px" class="ta-right textarea-tip"> {{ form.remark ? form.remark.length : 0 }}/50字 </a-row>
          </a-form-model-item>
        </a-form-model>
        <!--  -->
        <a-modal v-model="addVisible" title="新增定薪模板" @ok="handleAddOk" @cancel="handleAddCancel">
          <a-form-model ref="addForm" :model="addForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-model-item label="模板名称" prop="name">
              <a-input v-model="addForm.name" placeholder="请填写" />
            </a-form-model-item>
            <a-form-model-item label="定薪项" prop="itemIds">
              <div class="fix-salary-item-wrapper">
                <div v-for="(item, index) in fixItems" :key="index" :class="computeItemClass(item)" @click="handleAddSelected(item)">
                  <span>
                    {{ item.name }}
                  </span>
                </div>
              </div>
            </a-form-model-item>
          </a-form-model>
        </a-modal>

        <a-divider />
        <a-row class="file-foot-save">
          <a-col class="fr">
            <a-button class="mg_r10" @click="goOut">取消</a-button>
            <a-button type="primary" @click="handleSubmit">保存</a-button>
          </a-col>
        </a-row>
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>
<script>
const columns = [
  {
    title: "定薪项目",
    dataIndex: "itemName",
    align: "itemName",
    key: "itemName",
    scopedSlots: { customRender: "itemName" },
    width: 150
  },
  {
    title: "试用期工资",
    dataIndex: "trial",
    align: "trial",
    key: "trial",
    scopedSlots: { customRender: "trial" },
    width: 150
  },
  {
    title: "转正后工资",
    dataIndex: "formal",
    align: "formal",
    key: "formal",
    scopedSlots: { customRender: "formal" },
    width: 150
  }
];
import { selectByCompanyId, detaiByempId, empWage, addSalaryTemplate } from "@/api/wages/file";
import { mapState } from "vuex";
const fixItems = [
  {
    id: 1,
    name: "基本工资",
    selected: true,
    isDefault: true
  },
  {
    id: 2,
    name: "交通补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 3,
    name: "住房补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 4,
    name: "全勤奖",
    selected: false,
    isDefault: false
  },
  {
    id: 5,
    name: "餐补",
    selected: false,
    isDefault: false
  },
  {
    id: 6,
    name: "高温补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 7,
    name: "工龄补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 8,
    name: "夜班津贴",
    selected: false,
    isDefault: false
  },
  {
    id: 9,
    name: "通讯补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 10,
    name: "节假日补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 11,
    name: "员工慰问金",
    selected: false,
    isDefault: false
  },
  {
    id: 12,
    name: "推荐奖",
    selected: false,
    isDefault: false
  },
  {
    id: 13,
    name: "职务津贴",
    selected: false,
    isDefault: false
  },
  {
    id: 14,
    name: "绩效工资",
    selected: false,
    isDefault: false
  },
  {
    id: 15,
    name: "季度奖",
    selected: false,
    isDefault: false
  },
  {
    id: 16,
    name: "销售提成",
    selected: false,
    isDefault: false
  },
  {
    id: 17,
    name: "计件工资",
    selected: false,
    isDefault: false
  },
  {
    id: 18,
    name: "工龄工资",
    selected: false,
    isDefault: false
  },
  {
    id: 19,
    name: "司龄工资",
    selected: false,
    isDefault: false
  },
  {
    id: 20,
    name: "职称工资",
    selected: false,
    isDefault: false
  },
  {
    id: 21,
    name: "技能工资",
    selected: false,
    isDefault: false
  },
  {
    id: 22,
    name: "学历工资",
    selected: false,
    isDefault: false
  }
];
export default {
  name: "FileAdd",

  data() {
    return {
      fixedSalaryTemplateName: null,
      fixItems,
      addForm: {
        name: ""
      },
      addVisible: false,
      lastId: "",
      lastName: "",
      buttonState: false,
      form: {},
      empName: "",
      detailsListCopy: [],
      trialTemplateList: [],
      formalTemplateList: [],
      detailsList: [],
      templateId: "",
      templateList: [],
      companyId: this.$store.state.hr.companyId,
      desc: "",
      columns,
      routerData: {},
      rules: {
        name: [{ required: true, message: "必填", trigger: "blur" }]
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      currentPage: null
    };
  },
  computed: {
    ...mapState(["hr"]),
    status() {
      return ["待入职", "入职", "待离职", "离职"][this.routerData.status - 1];
    },
    doWords() {
      return ["salaryPerformance", "mealSubsidy", "trafficSubsidy", "salaryBasic"];
    },
    postType() {
      return this.$store.state.enums.postTypeArr;
    },
    allmoney() {
      const { salaryPerformance, mealSubsidy, trafficSubsidy, salaryBasic } = this.postData;
      const arr = [salaryPerformance, mealSubsidy, trafficSubsidy, salaryBasic];
      return arr.reduce((preValue, curValue) => Number(preValue) + Number(curValue), 0);
    },
    reasons() {
      return [
        { label: "转正", value: 1 },
        { label: "晋升", value: 2 },
        { label: "调动", value: 3 },
        { label: "年中调薪", value: 4 },
        { label: "年度调薪", value: 5 },
        { label: "特别调薪", value: 6 },
        { label: "其他", value: 7 }
      ];
    }
  },

  created() {
    this.routerData = JSON.parse(this.$route.query.routerData);
    this.currentPage = this.$route.query.currentPage;
    this.getSelectByCompanyId();

    // this.getDetaiByempId()
  },

  beforeDestory() {
    this.clearInterval(this.timer);
  },
  methods: {
    goBack() {
      this.$router.push({
        path: "/wages/file",
        query: {
          currentPage: this.currentPage
        }
      });
    },
    handleAddSelected(item) {
      if (item.id === 1) return;
      item.selected = !item.selected;
    },
    computeItemClass(item) {
      if (item.id === 1) return "fix-salary-item-tag fix-salary-item-default";
      if (item.selected) return "fix-salary-item-tag fix-salary-item-selected";
      return "fix-salary-item-tag";
    },
    handleAddCancel() {
      this.$refs.addForm.clearValidate();
    },
    handleAddOk() {
      const arr = this.fixItems.filter((item, index) => {
        if (item.selected) return true;
      });
      const data = {
        companyId: this.companyId,
        isDefault: false,
        name: this.addForm.name,
        itemIds: arr.map((item) => item.id).join(",")
      };
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          addSalaryTemplate(data)
            .then((res) => {
              this.addVisible = false;
              this.getSelectByCompanyId();
            })
            .catch((err) => {
              console.log("debug log --> ", err);
            });
        }
      });
    },
    goIncrease() {
      this.addVisible = true;
      this.addForm = {};
      this.fixItems.forEach((item, index) => {
        if (index > 0) item.selected = false;
      });
      // this.$router.push({
      //   path: '/wages/file/template'
      // })
    },
    templateChange(id, key, item) {
      // item.style = "buttonStyleClick";
      this.templateList[0].style = null;
      this.fixedSalaryTemplateName = item.name;
      // this.templateList[0].color = null;
      for (var i = 0; i < this.templateList.length; i++) {
        if (this.templateList[i].id === id) {
          this.templateList[i].style = "buttonStyleClick";
        } else {
          this.templateList[i].style = null;
        }
      }
      this.detailsList = [];
      this.templateId = id;
      this.detailsList;
      this.getDetaiByempId();
    },
    getDetaiByempId() {
      const id = this.templateId ? this.templateId : this.lastId;
      detaiByempId(id).then((res) => {
        this.detailsList = res.data;
        this.trialTemplateList = JSON.parse(JSON.stringify(res.data));
        this.formalTemplateList = JSON.parse(JSON.stringify(res.data));
        for (var i = 0; i < this.detailsList.length; i++) {
          this.detailsList[i].projectId = i;
          this.detailsList[i].trial = this.detailsList[i].trial ? this.detailsList[i].trial : 0;
          this.detailsList[i].formal = this.detailsList[i].formal ? this.detailsList[i].formal : 0;
        }
      });
    },
    getSelectByCompanyId() {
      selectByCompanyId({ companyId: this.companyId }).then((res) => {
        this.templateList = res.data;
        this.templateList.forEach((item, index) => {
          this.templateList[0].style = "buttonStyleClick";
        });
        this.templateId = this.templateList[0].id;
        this.lastId = this.templateList[0].id;
        this.lastName = this.templateList[0].name;
        // this.templateList[0].color = "#6A66F6";
        this.getDetaiByempId();
      });
    },
    goOut() {
      const _this = this;
      this.$confirm({
        title: "员工定薪尚未保存，是否确认离开？",
        okText: "确定",
        cancelText: "取消",
        onOk() {
          _this.$router.go(-1);
        }
      });
    },
    // 表格输入框变化
    handleInputChange(value, key, col) {
      const arr = JSON.parse(JSON.stringify(this.detailsList));
      if (col === "trial") {
        for (var i = 0; i < arr.length; i++) {
          if (i === key) {
            arr[i].trial = value;
            this.trialTemplateList[i].amount = value;
            this.trialTemplateList[i].name = this.trialTemplateList[i].itemName;
            // this.trialTemplateList[i].projectId = key
          }
        }
        var s = 0;
        for (var t = 0; t < arr.length - 1; t++) {
          s += arr[t].trial;
          arr[arr.length - 1].trial = s;
          this.trialTemplateList[this.trialTemplateList.length - 1].amount = s;
        }
      }
      if (col === "formal") {
        for (var p = 0; p < arr.length; p++) {
          if (p === key) {
            arr[p].formal = value;
            this.formalTemplateList[p].amount = value;
            this.formalTemplateList[p].name = this.formalTemplateList[p].itemName;
            // this.formalTemplateList[p].projectId = key
          }
        }
        var sum = 0;
        for (var a = 0; a < arr.length - 1; a++) {
          sum += arr[a].formal;
          arr[arr.length - 1].formal = sum;
          this.formalTemplateList[this.formalTemplateList.length - 1].amount = sum;
        }
      }

      this.detailsList = JSON.parse(JSON.stringify(arr));
    },
    // 表单提交
    handleSubmit() {
      for (var i = 0; i < this.detailsList.length; i++) {
        this.trialTemplateList[i].amount = this.trialTemplateList[i].amount ? this.trialTemplateList[i].amount : 0;
        this.formalTemplateList[i].amount = this.formalTemplateList[i].amount ? this.formalTemplateList[i].amount : 0;
      }
      empWage({
        fixedSalaryTemplateName: this.fixedSalaryTemplateName ? this.fixedSalaryTemplateName : this.lastName,
        isFixed: 1,
        isOfficial: parseInt(this.routerData.employType),
        companyId: this.companyId,
        empId: this.routerData.empId,
        fixedSalaryTemplateId: this.templateId ? this.templateId : this.lastId,
        reason: 0,
        trainingFixedSalaryDetail: JSON.stringify(this.trialTemplateList),
        officialFixedSalaryDetail: JSON.stringify(this.formalTemplateList),
        officialSalarySum: this.formalTemplateList[this.formalTemplateList.length - 1].amount
          ? this.formalTemplateList[this.formalTemplateList.length - 1].amount
          : 0,
        trainingSalarySum: this.trialTemplateList[this.trialTemplateList.length - 1].amount
          ? this.trialTemplateList[this.trialTemplateList.length - 1].amount
          : 0,
        remark: this.form.remark
      }).then(({ success }) => {
        if (success) {
          this.goBack();
          this.$notification["success"]({ message: "定薪成功" });
        }
      });
    },
    onChange() {}
  }
};
</script>
<style lang="scss" scoped>
$body-width: calc(100% - 338px);

.fix-salary-item-wrapper {
  width: 400px;
  .fix-salary-item-tag {
    cursor: pointer;
    height: 28px;
    line-height: 28px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #d7d7d7;
    display: inline-block;
    font-size: 12px;
    margin-right: 10px;
    padding: 0 5px;
  }
  .fix-salary-item-default {
    background: #ededed;
    border-color: #a2a2a2;
  }
  .fix-salary-item-selected {
    background: #ffffff;
    border: 1px solid var(--primary);
    color: var(--primary);
  }
}
.border-r-line {
  border: #adadad;
}
.modelBotton {
  margin-left: 15px;
}
.buttonStyleClick {
  margin-left: 15px;
  border: 1px solid var(--primary);
  color: var(--primary);
}
</style>
